package com.bestcem.xm.txtanls.controller;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.txtanls.controller.convert.KeywordConvert;
import com.bestcem.xm.txtanls.controller.vo.keyword.ListKeywordVO;
import com.bestcem.xm.txtanls.grpc.service.param.keyword.ListKeywordParam;
import com.bestcem.xm.txtanls.grpc.service.param.keyword.UpdateKeywordParam;
import com.bestcem.xm.txtanls.service.KeywordService;
import com.bestcem.xm.txtanls.service.dto.keyword.ListKeywordDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import java.util.Optional;
import java.util.Set;

import static com.bestcem.xm.common.core.constant.Constants.ONE;

/**
 * 关键词controller类
 *
 * @author liheng
 * @version v2.0
 * @date 2021/8/5 20:34
 */
@RestController
@RequestMapping(value = "/txtanls/keywords", produces = MediaType.APPLICATION_JSON_VALUE)
public class KeywordController {

    @Resource
    private KeywordService keywordService;

    /**
     * 查询关键词或被屏蔽关键词
     *
     * @param projectId 文本分析项目id
     * @param status    1-关键词，0-被屏蔽关键词（默认为1）
     * @param fieldId   分析字段id
     * @return 关键词list以及原话匹配率
     */
    @GetMapping("/")
    public XmResultJson<ListKeywordVO> listKeyword(@RequestParam("projectid") String projectId,
                                                   @RequestParam(value = "status", required = false) Integer status,
                                                   @RequestParam(value = "field_id", required = false) String fieldId,
                                                   HttpServletRequest request) {

        String orgId = SecurityContextHolder.getOrgId();
        if (!ObjectId.isValid(projectId)) {
            return XmResultJson.fail(4, "缺少项目id");
        }
        Integer defaultStatus = Optional.ofNullable(status).orElse(ONE);

        if (StringUtils.isBlank(orgId)) {
            return XmResultJson.fail(4, "orgId错误");
        }
        ListKeywordParam listKeywordParam = new ListKeywordParam(projectId, defaultStatus, fieldId, orgId);
        ServiceResult<ListKeywordDTO> result = keywordService.listKeyword(listKeywordParam);
        if (result.isSuccess()) {
            ListKeywordVO listKeywordVO = KeywordConvert.keywordToVo(result.getData());
            return XmResultJson.success(listKeywordVO);
        } else {
            return XmResultJson.fail(5, result.getMsg());
        }


    }

    /**
     * 屏蔽关键词
     *
     * @param param {projectId 文本分析项目id  keyword   关键词   status    1-屏蔽关键词，0-删除屏蔽关键词（即取消屏蔽）}
     * @return XmResultJson<Object>
     */
    @PutMapping("/")
    public XmResultJson<Object> updateKeyword(@RequestBody UpdateKeywordParam param) {
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(5, violation.getMessage());
        }
        Integer defaultStatus = Optional.of(param.getStatus()).orElse(ONE);
        UpdateKeywordParam updateKeywordParam = new UpdateKeywordParam(param.getProjectId(), param.getKeyword(), defaultStatus);
        ServiceResult<Object> result = keywordService.updateKeyword(updateKeywordParam);
        if (result.isSuccess()) {
            return XmResultJson.success(param.getProjectId());
        } else {
            return XmResultJson.fail(5, result.getMsg());
        }
    }


}
